import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { getFakeCaptcha } from '@/services/api';
import { login, getVerifyCode } from '@/services/user';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    currentUser: {},
    loading: true,
  },

  effects: {
    *login({ payload }, { call, put }) {
      // 触发登录事件
      const response = yield call(login, payload);
      // response用户信息
      window.localStorage.setItem('currentUser', JSON.stringify(response)); // 设置当前登录用户信息
      window.localStorage.setItem('robotId', response.robotId);
      window.localStorage.setItem('robotName', response.robotName);
      window.localStorage.setItem('uid', response.uid);
      window.localStorage.setItem('nick', response.nick);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (!response.code) {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },
    *getCode({ payload, callback }, { call, put }) {
      const response = yield call(getVerifyCode, payload);
      if (response) {
        if (callback && typeof callback === 'function') {
          callback(response);
        }
        yield put({
          type: 'save',
          payload: response,
        });
      }
    },
    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          roles: ['guest'],
        },
      });
      // 删除缓存的用户信息
      window.localStorage.removeItem('currentUser');
      // 删除缓存的用户等级
      window.localStorage.removeItem('antd-pro-authority');
      window.localStorage.removeItem('robotId');
      window.localStorage.removeItem('robotName');
      window.localStorage.removeItem('token');
      window.localStorage.removeItem('uid');
      window.localStorage.removeItem('nick');
      // clearInterval(checkTime);
      // clearInterval(checkAction);
      reloadAuthorized();
      // redirect
      if (window.location.pathname !== '/user/login') {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: '',
            }),
          })
        );
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority('admin');
      return {
        ...state,
        currentUser: payload,
        loading: false,
      };
    },
  },
};
